﻿using System;
using UnityEngine;
using System.Collections.Generic;

[DisallowMultipleComponent]
public class ReferenceGroup : ReferenceUnit
{
    [Serializable]
    public struct Data
    {
        public string name;
        public GameObject go;
    }

    [HideInInspector]
    [SerializeField]
    List<Data> references = new List<Data>();
    Dictionary<string, GameObject> referenceDic = new Dictionary<string, GameObject>();

    bool isInitReference;
    void InitReference()
    {
        if (isInitReference)
            return;
        isInitReference = true;

        foreach (var item in references)
        {
            referenceDic[item.name] = item.go;
        }
    }

    public bool IsExist(string goName)
    {
        InitReference();
        return referenceDic.ContainsKey(goName);
    }

    public T GetReference<T>(string goName) where T : Component
    {
        InitReference();

        GameObject go = null;
        if (!referenceDic.TryGetValue(goName, out go))
        {
            go = new GameObject($"{goName}(create)");
            Debug.LogError($"can not get gameobject: {goName}");

            if (typeof(T) != typeof(Transform))
                return go.AddComponent<T>();
        }

        var com = go.GetComponent<T>();
        if(com == null)
        {
            Debug.LogError($"can not get component: {typeof(T)}, name: {goName}");
            return go.AddComponent<T>();
        }

        return com;
    }

    public GameObject GetReference(string goName)
    {
        InitReference();

        GameObject go = null;
        if (!referenceDic.TryGetValue(goName, out go))
        {
            go = new GameObject($"{goName}(create)");
            Debug.LogError($"can not get gameobject: {goName}");
        }

        return go;
    }
}
